import React, { PureComponent } from 'react'

import { connect } from 'dva'
// import Search from '../Search/index';
import LZSearch from '@/components/Search'

import moment from 'moment'
import { uploadUrl } from '@/config/index'
import { PageHeaderWrapper } from '@ant-design/pro-layout'
import CopyToClipboard from '@/components/CopyToClipboard'
import { openLinkInNewWindow } from '@/utils/utils'

// import { getToken } from '@/utils/localStorage';
function getToken() {
  const token = localStorage.getItem('token')
  return token
}
import {
  Table,
  Card,
  message,
  Tooltip,
  Button,
  Modal,
  Icon,
  Drawer,
  Form,
  Input,
  Select,
  Cascader,
  Spin,
  Upload
} from 'antd'

import MyPageTable from '@/components/MyPageTable'
import { onTableData } from '@/utils/utils.js'
import { router } from 'umi'
const getStatus = new Map([
  [1, '已上架'],
  [2, '未上架']
])
const { Option } = Select

function debounce(func, wait) {
  let timeout
  return function() {
    let context = this
    let args = arguments

    if (timeout) clearTimeout(timeout)

    let callNow = !timeout
    timeout = setTimeout(() => {
      timeout = null
    }, wait)

    if (callNow) func.apply(context, args)
  }
}

@connect(({ goodsIndex, loading }) => ({
  ...goodsIndex,
  editGoods: loading.effects['goodsIndex/selectExaminePoroductDirectBuyList']
}))
@Form.create()
class Index extends PureComponent {
  state = {
    loading: true,
    arrStatus: ['0/正在审核', '1/审核不通过', '2/审核通过'],
    current: 1,
    pageNumber: 1,
    pageSize: 10,
    auditState: null,
    creatTime: [],
    type: null,
    productId: null,
    productName: null,
    shopId: null,
    shopName: null,
    status: null,
    visible: false,
    spinning: false,
    fileList: [],
    imgSrc: null,
    imgVisible: false,
    a: 0
  }

  componentDidMount() {
    if (this.props.location.query && this.props.location.query.id) {
      this.setState(
        {
          productId: this.props.location.query.id
        },
        () => this.initData()
      )
    } else {
      this.initData()
    }
  }

  initData = e => {
    let payload = {
      auditState: this.state.auditState,
      creatTime: this.state.creatTime,
      type: this.state.type,
      pageNumber: this.state.pageNumber,
      pageSize: this.state.pageSize,
      productId: e === '修改' ? '' : this.state.productId,
      productName: this.state.productName,
      shopId: this.state.shopId,
      shopName: this.state.shopName,
      status: this.state.status
    }
    this.setState(
      {
        loading: true
      },
      () => {
        this.props.dispatch({
          type: 'goodsIndex/selectExaminePoroductDirectBuyList',
          payload,
          callback: res => {
            if (res.responseType === 'SUCCESS') {
              message.success('获取信息成功')
              this.setState({
                total: res.data.total,
                loading: false,
                current: res.data.current
              })
            } else {
              message.error(res.data.msg)
            }
          }
        })
      }
    )
  }

  handleFilter = (data = {}) => {
    console.log(data, 'data')
    if (data.type && data.type === '重置') {
      this.setState(
        {
          auditState: null, //审核状态
          pageNumber: 1,
          pageSize: 10,
          creatTime: null,
          type: null, //是否上架
          productId: null,
          productName: null,
          shopId: null,
          shopName: null,
          status: null //是否失效
        },
        () => {
          this.initData()
        }
      )
    } else if (data.type && data.type === '分页') {
      this.initData()
    } else {
      this.setState(
        {
          auditState: data.auditState === '全部' ? null : data.auditState, //审核状态
          pageNumber: 1,
          pageSize: 10,
          creatTime: data.creatTime
            ? [
                moment(data.creatTime[0]).format('YYYY-MM-DD HH:mm:ss'),
                moment(data.creatTime[1]).format('YYYY-MM-DD HH:mm:ss')
              ]
            : null,
          type: data.type ? data.type : null,
          productId: data.productId ? data.productId : null,
          productName: data.productName ? data.productName : null,
          shopId: data.shopId ? data.shopId : null,
          shopName: data.shopName ? data.shopName : null,
          status: data.goodStatus ? data.goodStatus : null
        },
        () => {
          this.initData()
        }
      )
    }
  }

  //分页，下一页
  onChange = pageNumber => {
    this.setState(
      {
        pageNumber: pageNumber.current
      },
      () => {
        this.handleFilter({ type: '分页' })
      }
    )
  }
  // showTotal = () => {
  //   return `共有${this.state.total}条`;
  // };
  //切换每页数量
  onShowSizeChange = (current, pageSize) => {
    this.setState({ pageSize: pageSize }, () => {
      this.handleFilter({ type: '分页' })
    })
  }

  //商品编辑
  edit = id => {
    this.modifyProductId = id // 修改商品，this.state.productId是用来请求分页数据的
    this.setState(
      {
        // visible: true,
        spinning: true,
        imgVisible: true
      },
      () => {
        // 不用延时会出现drawer卡顿的现象
        setTimeout(() => {
          this.props.dispatch({
            type: 'goodsIndex/selectExamineProductDirectBuyEdit',
            payload: {
              productId: id
            },
            callback: res => {
              if (res.responseType === 'SUCCESS') {
                message.success('获取商品编辑信息成功')
                this.setState({
                  spinning: false,
                  fileList: res.data.uploadImg
                })
              } else {
                message.error('获取商品编辑信息失败' + res.data.msg)
              }
            }
          })
          this.props.dispatch({
            type: 'goodsIndex/editGoodsCategory',
            callback: res => {
              // console.log(res);
            }
          })
        }, 500)
      }
    )
  }

  onClose = () => {
    this.setState({
      visible: false
    })
    this.props.form.resetFields()
  }

  handleChange = ({ file, fileList, event }) => {
    debugger
    // console.log('当前文件对象',file);
    console.log('当前的文件列表', fileList)
    // console.log('上传中的服务端响应内容',event);
    let newFileList = fileList.map(item => {
      if (item.src) {
        return item.src
      } else if (file.status === 'done') {
        return item.response.data
      }
    })
    console.log('newFileList:', newFileList)
    this.props.dispatch({
      type: 'goodsIndex/saveUploadImg',
      payload: fileList,
      callback: res => {
        if (res.data.msg !== '操作成功') {
          message.error(res.data.msg)
        }
      }
    })
    if (file.status === 'done') {
      message.success(`${file.name} 上传成功！`)
      this.setState({
        fileList: newFileList
      })
    }
  }

  // 上传组件的预览
  handlePreview = () => {
    this.setState({
      imgVisible: true
    })
  }
  // 上传组件的删除，不需要进行操作，antd已经封装好了
  onRemove = file => {
    this.setState({
      fileList: this.state.fileList.filter(item => item.url !== file.url)
    })
    return true
  }

  handleImgCancel = () => {
    this.setState({
      imgVisible: false
    })
  }
  //函数防抖
  submit = debounce(() => {
    this.props.form.validateFields((err, value) => {
      if (!err) {
        let payload = {
          categoryId: value.category[value.category.length - 1],
          id: this.props.editInfo.product.id,
          maxAdvancedDays: value.maxAdvancedDays,
          maxRentCycle: value.maxRentCycle,
          minAdvancedDays: value.minAdvancedDays,
          minRentCycle: value.minRentCycle,
          name: value.name,
          shopId: value.email,
          type: value.status,
          productId: this.modifyProductId,
          images: this.state.fileList.map(item => {
            console.log(item, 'item.srcitem.src')
            if (item.src) {
              return item.src
            } else {
              return item
            }
          }),
          renewStatus: value.renewStatus,
          buyoutStatus: value.buyoutStatus
        }
        // debugger
        this.props.dispatch({
          type: 'goodsIndex/updateExamineProductDirectBuy',
          payload: payload,
          callback: res => {
            if (res.responseType === 'SUCCESS') {
              message.success('编辑成功')
              this.setState(
                {
                  visible: false,
                  imgVisible: false
                },
                () => {
                  this.initData('修改')
                }
              )
              this.props.form.resetFields()
            } else {
              message.error(res.data.msg)
            }
          }
        })
      }
    })
  }, 2000)
  onCopy = e => {
    // console.log('上传中的服务端响应内容', e);
    message.success(`复制内容：${e}`)
  }
  render() {
    const {
      loading,
      current,
      total,
      arrStatus,
      visible,
      spinning,
      fileList,
      imgSrc,
      imgVisible
    } = this.state
    const { list, editInfo, editSelectData } = this.props
    const paginationProps = {
      current: this.state.current,
      pageSize: 10,
      total: this.state.total,
      showTotal: total => (
        <span style={{ fontSize: '14px' }}>
          <span>共{Math.ceil(total / 10)}页</span>&emsp;
          <span>共{total}条</span>
        </span>
      )
    }
    const { getFieldDecorator } = this.props.form
    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 6 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 }
      }
    }
    const uploadButton = (
      <div>
        <Icon type="plus" />
        <div className="ant-upload-text">Upload</div>
      </div>
    )
    let auditStateData = {
      0: '正在审核中',
      1: '审核不通过',
      2: '审核通过'
    }
    const columns = [
      // {
      //   title: '店铺编号',
      //   dataIndex: 'shopId',
      //   width: '10%',
      //   render: shopId => <CopyToClipboard text={shopId} />,
      // },
      {
        title: '店铺名称',
        dataIndex: 'shopName',
        width: '10%'
      },
      {
        title: '商品编号',
        dataIndex: 'productId',
        width: '10%',
        render: productId => <CopyToClipboard text={productId} />
      },
      {
        title: '购买价格',
        dataIndex: 'sale',
        width: '10%'
      },
      {
        title: '商品名称',
        dataIndex: 'name',
        width: '10%'
      },
      // {
      //   title: '商品类目',
      //   dataIndex: 'opeCategoryStr',
      //   width: '10%',
      // },
      {
        title: '上架状态',
        dataIndex: 'type',
        render: text => getStatus.get(text),
        width: '10%'
      },
      {
        title: '提交时间',
        dataIndex: 'updateTime',
        width: '10%'
      },
      {
        title: '审核状态',
        dataIndex: 'auditState',
        render: text => <span>{auditStateData[text]}</span>,
        width: '10%'
      },
      {
        title: '操作',
        width: '10%',
        render: (text, record) => {
          return (
            <div>
              <a
                onClick={() =>
                  openLinkInNewWindow(
                    `/goods/Purchase/goodsDetail/id=${record.productId}/actionId=${record.id}`
                  )
                }
              >
                查看
              </a>
              <a
                style={{ whiteSpace: 'nowrap', paddingLeft: 5 }}
                onClick={() => this.edit(record.productId)}
              >
                修改
              </a>
            </div>
          )
        }
      }
    ]

    return (
      <PageHeaderWrapper>
        <Card bordered={false}>
          <LZSearch
            needReset
            source="商品审核"
            handleFilter={this.handleFilter}
          />
        </Card>
        <Card bordered={false} style={{ marginTop: 20 }}>
          <MyPageTable
            onPage={this.onChange}
            paginationProps={paginationProps}
            dataSource={onTableData(list)}
            columns={columns}
          />
        </Card>
        <Drawer
          title="商品编辑"
          placement="right"
          onClose={this.onClose}
          visible={visible}
          width={550}
        />
        <Modal
          visible={imgVisible}
          footer={null}
          title={'修改'}
          onCancel={this.handleImgCancel}
          width={600}
          destroyOnClose
        >
          <Spin spinning={this.props.editGoods}>
            <Form {...formItemLayout}>
              <Form.Item label="商品类目">
                {getFieldDecorator('category', {
                  rules: [
                    {
                      required: true,
                      message: '商品类目不能为空'
                    }
                  ],
                  initialValue:
                    editInfo &&
                    editInfo.category &&
                    editInfo.category.categoryId
                })(
                  <Cascader
                    options={editSelectData && editSelectData}
                    placeholder="请选择类目"
                  />
                )}
              </Form.Item>
              <Form.Item label="商品名称">
                {getFieldDecorator('name', {
                  rules: [
                    {
                      required: true,
                      message: '商品名称不能为空'
                    }
                  ],
                  initialValue:
                    editInfo && editInfo.product && editInfo.product.name
                })(<Input allowClear={true} />)}
              </Form.Item>
              <Form.Item label="商品状态">
                {getFieldDecorator('status', {
                  rules: [
                    {
                      required: true,
                      message: '商品状态不能为空'
                    }
                  ],
                  initialValue: `${editInfo &&
                    editInfo.product &&
                    editInfo.product.status}`
                })(
                  <Select allowClear={true}>
                    <Option value="1">上架</Option>
                    <Option value="0">未上架</Option>
                  </Select>
                )}
              </Form.Item>
              <Form.Item label="图片上传">
                {getFieldDecorator('upload', {
                  rules: [
                    {
                      required: true,
                      message: '请上传图片，图片不能为空'
                    }
                  ],
                  initialValue: editInfo && editInfo.uploadImg
                })(
                  <Upload
                    accept="image/*"
                    action={uploadUrl}
                    headers={{
                      token: getToken()
                    }}
                    listType="picture-card"
                    fileList={editInfo && editInfo.uploadImg}
                    // onPreview={this.handlePreview} //预览
                    onRemove={this.onRemove} //删除
                    onChange={this.handleChange}
                  >
                    {fileList.length >= 8 ? null : uploadButton}
                  </Upload>
                )}
              </Form.Item>
              <Form.Item wrapperCol={{ span: 24 }}>
                <div style={{ textAlign: 'center' }}>
                  <Button type="primary" size="large" onClick={this.submit}>
                    提交
                  </Button>
                </div>
              </Form.Item>
            </Form>
          </Spin>
        </Modal>
      </PageHeaderWrapper>
    )
  }
}

export default Index
